package com.office.shop.by;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import com.office.shop.by.components.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import static android.graphics.BitmapFactory.decodeResource;


public class MultiAccActivity extends Activity {

    private ProgressDialog pd;
    public static MultiAccActivity obj;
    public static SharedPreferences sharedPreferences;
    public static int current_acc;
    public  static  ListView lvAccs;

    static ArrayList<HashMap<String,Object>> list =new ArrayList<HashMap<String,Object>>();
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        obj = this;
        sharedPreferences =  getPreferences(0);
        setContentView(R.layout.loading);
        CAccounts.init(MultiAccActivity.this);
        Refresh();
    }


    public void Refresh() {
       pd = ProgressDialog.show(this, "", getString(R.string.DataUpdate), true, false);
       new JSONParser().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
           MenuInflater inflater = getMenuInflater();
           inflater.inflate(R.menu.multiacc_menu, menu);
           return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.mmAccs:
                     Intent i = new Intent();
                     i.setClass(this, AccountsActivity.class);
                     i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                     startActivity(i);
            return true;
            case R.id.mmRefresh:
            this.Refresh();
            return true;
            case R.id.mmExit:
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }


    private void populateList(JSONObject[] output) {
        try {
            for (int i = 0; i< CAccounts.logins.length; i++)
            {
                if(output[i]!=null)
                {
                    HashMap<String,Object> temp = new HashMap<String,Object>();
                    JSONObject json_data = output[i];
                    Bitmap img = CImages.fetchImage(json_data.getString("img_url"));
                    if(img != null)
                        temp.put("icon",img);
                    else
                        temp.put("icon",decodeResource(getResources(), R.drawable.icon));

                    temp.put("url",json_data.getString("real_url"));
                    temp.put("sum", CFormat.numberFormat(json_data.getJSONObject("host").getString("purse_sum")));
                    temp.put("status", getFullStatus(json_data.getJSONObject("db").getString("status")));
                    temp.put("pos",i);
                    list.add(temp);

                }
            }
        } catch (JSONException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }


}
    public SharedPreferences getSharedPreferences()
    {
        return  sharedPreferences;
    }

    private String getFullStatus(String status)
    {
        if(status.equals("active"))
            return getString(R.string.ServiceActive);
        else
            return getString(R.string.ServiceNoActive);
    }

    private void createAccountList(JSONObject[] output)
    {
        if(output != null)
            {
                list = new ArrayList<HashMap<String,Object>>();
                setContentView(R.layout.multiacc);
                lvAccs = (ListView)findViewById(R.id.lvAccs);
                SimpleAdapter simpleAdapter = new SimpleAdapter(MultiAccActivity.this,
                                list,
                                R.layout.multiacc_row,
                                new String[] {"icon","url","sum","status","pos"},
                                new int[] {R.id.ibIcon, R.id.txtShopUrl,R.id.txtShopBalance,R.id.txtShopStatus,R.id.txtShopPos});
               simpleAdapter.setViewBinder(new MultiAccViewBinder());
               populateList(output);
               simpleAdapter.notifyDataSetChanged();
               lvAccs.setAdapter(simpleAdapter);
               lvAccs.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            }
            else
            {
               setContentView(R.layout.login);
            }
    }

    public void itemClick(View v)
    {

        TextView textView = (TextView)v.findViewById(R.id.txtShopPos);
        current_acc = Integer.parseInt(textView.getText().toString());
        Intent i = new Intent();
        i.setClass(this, OfficeActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);


    }

    public class MultiAccViewBinder implements SimpleAdapter.ViewBinder {
                public boolean setViewValue(View view, Object data, String textRepresentation) {
                        if( (view instanceof ImageButton) & (data instanceof Bitmap) )
                        {
                                ImageButton iv = (ImageButton) view;
                                Bitmap bm = (Bitmap) data;
                                iv.setImageBitmap(bm);
                                return true;

                        }
                        return false;

                }

    }

    public class JSONParser extends AsyncTask<String, Void, JSONObject[]> {
        //Фоновая операция
        protected JSONObject[] doInBackground(String arg[]) {
          JSONObject[] output = new JSONObject[CAccounts.logins.length];
          try
          {
            for (int i = 0; i < CAccounts.logins.length; i++)
            {
                if(CAuth.login(CAccounts.logins[i], CAccounts.passwords[i]))
                   output[i] = CHttp.postJSON((CConfig.serverUrl), CAuth.getLogin());
                else
                   output[i] = null;
            }
          }
          catch(Exception e)
          {
            e.printStackTrace();
          }
          return output;
        }

        //Событие по окончанию парсинга
        protected void onPostExecute(JSONObject[] output) {
            createAccountList(output);
            pd.dismiss();
        }
    }
}
